package info.wangyuan.agent.interceptor;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import info.wangyuan.agent.config.UserContext;
import info.wangyuan.agent.entity.po.User;
import info.wangyuan.agent.service.curd.UserService;
import info.wangyuan.agent.utils.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * 认证拦截器
 *
 * @author Albert
 * @since 2025-09-11 20:04:56
 */
@Component
public class CertificationInterceptor implements HandlerInterceptor {

    private final UserService userService;
    private final JwtUtils jwtUtils;

    public CertificationInterceptor(UserService userService, JwtUtils jwtUtils) {
        this.userService = userService;
        this.jwtUtils = jwtUtils;
    }

    private static final String TOKEN_HEADER = "AiToken";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if (!HttpMethod.OPTIONS.matches(request.getMethod())) {
            String tokenString = request.getHeader(TOKEN_HEADER);
            if (StrUtil.isBlank(tokenString)) {
                // 没传 token，可以选择抛出异常或直接返回 401
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                return false;
            }
            if (!jwtUtils.validateToken(tokenString)) return false;
            String officialAccountsOpenid = jwtUtils.getOpenidFromToken(tokenString);

            User user = userService.getOne(Wrappers.lambdaQuery(User.class).eq(User::getOpenId, officialAccountsOpenid));
            if (user == null){
                // 用户不存在，同样返回 401
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                return false;
            }
            UserContext.setCurrentUser(user);
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        UserContext.clear();
    }
}
